import os
import random
from moviepy.editor import AudioFileClip, CompositeAudioClip
import logging
from typing import Optional, List

logger = logging.getLogger(__name__)

class AudioService:
    def __init__(self):
        self.audio_library = self._setup_audio_library()
        
    def _setup_audio_library(self):
        """设置音频库"""
        audio_library = {
            "background_music": [
                "assets/audio/background_1.mp3",
                "assets/audio/background_2.mp3",
                "assets/audio/background_3.mp3",
            ],
            "transition_sounds": [
                "assets/audio/transition_1.wav",
                "assets/audio/transition_2.wav",
            ],
            "effect_sounds": {
                "intro": "assets/audio/intro.wav",
                "outro": "assets/audio/outro.wav",
                "highlight": "assets/audio/highlight.wav",
            }
        }
        
        # 创建音频目录
        os.makedirs("assets/audio", exist_ok=True)
        
        return audio_library
    
    def get_background_music(self, duration: float, mood: str = "neutral") -> Optional[AudioFileClip]:
        """获取背景音乐"""
        try:
            # 根据情绪选择音乐（简化实现）
            music_files = self.audio_library["background_music"]
            
            # 过滤存在的文件
            available_music = [f for f in music_files if os.path.exists(f)]
            
            if not available_music:
                logger.warning("没有可用的背景音乐文件")
                return None
            
            # 随机选择一首音乐
            music_file = random.choice(available_music)
            
            # 加载音乐
            music = AudioFileClip(music_file)
            
            # 调整音乐长度以匹配视频
            if music.duration < duration:
                # 如果音乐比视频短，循环播放
                num_loops = int(duration / music.duration) + 1
                music = music.loop(n=num_loops)
            
            # 截取所需长度
            music = music.subclip(0, duration)
            
            # 调整音量
            music = music.volumex(0.3)  # 30%音量
            
            logger.info(f"✅ 加载背景音乐: {os.path.basename(music_file)}")
            return music
            
        except Exception as e:
            logger.error(f"❌ 加载背景音乐失败: {e}")
            return None
    
    def add_transition_sound(self, audio_clip: AudioFileClip, transition_time: float) -> AudioFileClip:
        """添加转场音效"""
        try:
            transition_files = self.audio_library["transition_sounds"]
            available_transitions = [f for f in transition_files if os.path.exists(f)]
            
            if not available_transitions:
                return audio_clip
            
            transition_file = random.choice(available_transitions)
            transition_sound = AudioFileClip(transition_file)
            
            # 在转场时间点添加音效
            transition_sound = transition_sound.set_start(transition_time)
            transition_sound = transition_sound.volumex(0.5)
            
            # 合并音效
            final_audio = CompositeAudioClip([audio_clip, transition_sound])
            
            logger.info(f"✅ 添加转场音效")
            return final_audio
            
        except Exception as e:
            logger.error(f"❌ 添加转场音效失败: {e}")
            return audio_clip
    
    def create_silent_audio(self, duration: float) -> AudioFileClip:
        """创建静音音频（备用）"""
        # 创建一个静音音频片段
        from moviepy.audio.AudioClip import AudioClip
        import numpy as np
        
        def make_silence(dt):
            return np.zeros((int(44100 * dt), 2))
        
        silent_audio = AudioClip(make_silence, duration=duration)
        silent_audio.fps = 44100
        
        return silent_audio
    
    def generate_audio_for_video(self, video_duration: float, script: dict) -> Optional[AudioFileClip]:
        """为视频生成完整的音频"""
        try:
            audio_clips = []
            
            # 1. 添加背景音乐
            bg_music = self.get_background_music(video_duration)
            if bg_music:
                audio_clips.append(bg_music)
            
            # 2. 根据脚本结构添加音效
            if audio_clips:
                # 合并所有音频
                final_audio = CompositeAudioClip(audio_clips)
                final_audio = final_audio.set_duration(video_duration)
                
                logger.info("✅ 音频生成完成")
                return final_audio
            else:
                # 如果没有背景音乐，返回静音
                logger.warning("使用静音音频")
                return self.create_silent_audio(video_duration)
                
        except Exception as e:
            logger.error(f"❌ 音频生成失败: {e}")
            return self.create_silent_audio(video_duration)